package com.business_clean.ui.activity.login;

import androidx.lifecycle.Observer;

import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.blankj.utilcode.util.DeviceUtils;
import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.NetworkUtils;
import com.blankj.utilcode.util.RegexUtils;
import com.business_clean.app.App;
import com.business_clean.app.base.BaseActivity;
import com.business_clean.app.callback.FetchAccessTokenCallBackImpl;
import com.business_clean.app.config.Constant;
import com.business_clean.app.config.ConstantMMVK;
import com.business_clean.app.ext.CommonUtils;
import com.business_clean.app.flutter.FlutterManager;
import com.business_clean.app.network.NetUrl;
import com.business_clean.app.uitl.ActivityForwardUtil;
import com.business_clean.app.uitl.AnimationUtils;
import com.business_clean.app.uitl.MMKVHelper;
import com.business_clean.app.uitl.ToastUtil;
import com.business_clean.app.weight.FullPortConfig;
import com.business_clean.data.mode.login.CodeEntity;
import com.business_clean.data.mode.login.UserInfo;
import com.business_clean.databinding.ActivityLoginBinding;
import com.business_clean.ui.activity.BaseH5Activity;
import com.business_clean.ui.activity.company.SelectCompanyActivity;
import com.business_clean.ui.activity.main.MainActivity;
import com.business_clean.viewmodel.request.LoginVideModel;
import com.idsmanager.doraemonlibrary.DoraemonManager;
import com.idsmanager.doraemonlibrary.callback.DoraemonCallback;
import com.idsmanager.doraemonlibrary.config.BaseUIConfig;
import com.lxj.xpopup.interfaces.OnSelectListener;
import com.mobile.auth.gatewayauth.PhoneNumberAuthHelper;

import org.jetbrains.annotations.Nullable;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.functions.Consumer;
import me.hgj.mvvmhelper.ext.AppExtKt;
import me.hgj.mvvmhelper.ext.LogExtKt;

public class LoginActivity extends BaseActivity<LoginVideModel, ActivityLoginBinding> {

    private String TAG = "LoginActivity";

    private static final long TIME_INTERVAL = 2000; // 两次点击间的最大时间间隔
    private long backPressedTime;

    private int changeClickCount = 0;//切换环境

    private Disposable disposable;


    @Override
    public void initView(@Nullable Bundle savedInstanceState) {

        if (NetUrl.defaultUrl.equals(NetUrl.SERVER_URL_RELEASE)) {
            mDatabind.tvLoginTitle.setText("登录");
        } else if (NetUrl.defaultUrl.equals(NetUrl.SERVER_URL_TEST)) {
            mDatabind.tvLoginTitle.setText("登录(测试)");
        } else {
            mDatabind.tvLoginTitle.setText("登录(开发)");
        }
        initAliAuthLogin();

        initbottom();
        //关闭除这个之外的所有
        AppExtKt.finishAllActivityExcept(this);
    }

    private void initbottom() {
        String agreementText = "我已阅读并同意服务协议和隐私协议";
        SpannableString spannableString = new SpannableString(agreementText);

        ClickableSpan serviceAgreementSpan = new ClickableSpan() {
            @Override
            public void onClick(View widget) {
                // 处理点击服务协议事件
                Bundle bundle = new Bundle();
                bundle.putString("url", Constant.SERVICE_AGREEMENT);
                ActivityForwardUtil.startActivity(BaseH5Activity.class, bundle);
            }

            @Override
            public void updateDrawState(TextPaint ds) {
                ds.setColor(Color.parseColor("#09BE89")); // 设置红色
                ds.setUnderlineText(false); // 取消下划线
            }
        };

        ClickableSpan privacyPolicySpan = new ClickableSpan() {
            @Override
            public void onClick(View widget) {
                // 处理点击隐私协议事件
                Bundle bundle = new Bundle();
                bundle.putString("url", Constant.PRIVACY_POLICY);
                ActivityForwardUtil.startActivity(BaseH5Activity.class, bundle);
            }

            @Override
            public void updateDrawState(TextPaint ds) {
                ds.setColor(Color.parseColor("#09BE89")); // 设置红色
                ds.setUnderlineText(false); // 取消下划线
            }
        };

        spannableString.setSpan(serviceAgreementSpan, 7, 11, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); // 设置服务协议的点击事件和颜色
        spannableString.setSpan(privacyPolicySpan, 12, agreementText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); // 设置隐私协议的点击事件和颜色

        mDatabind.tvBottom.setText(spannableString);
        mDatabind.tvBottom.setMovementMethod(LinkMovementMethod.getInstance());
    }


    @Override
    public void onBindViewClick() {
        mDatabind.butLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!mDatabind.checkbox.isChecked()) {
                    AnimationUtils.shakeAnimation(mDatabind.checkbox);
                    ToastUtil.show("必须同意服务协议");
                    return;
                }
                if (TextUtils.isEmpty(mDatabind.etLoginPass.getText().toString())) {
                    ToastUtil.show("请输入验证码");
                    return;
                }
                HashMap<String, String> hashMap = new HashMap<>();
                hashMap.put("mobile", "" + mDatabind.etLoginPhone.getText().toString());
                hashMap.put("code", "" + mDatabind.etLoginPass.getText().toString());
                hashMap.put("op_ip", "" + NetworkUtils.getIPAddress(true));
                hashMap.put("login_device", "" + DeviceUtils.getManufacturer() + DeviceUtils.getModel());
                mViewModel.loginApp(hashMap);
            }
        });

        //点击checkbox
        mDatabind.llServiceLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDatabind.checkbox.setChecked(!mDatabind.checkbox.isChecked());
            }
        });

        //这事清空Et
        mDatabind.ivLoginClean.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDatabind.etLoginPhone.setText("");
                mDatabind.ivLoginClean.setVisibility(View.GONE);
            }
        });

        //获取验证码
        mDatabind.butLoginCode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(mDatabind.etLoginPhone.getText().toString())) {
                    ToastUtil.show("请先输入手机号");
                    return;
                }
                if (!RegexUtils.isMobileExact(mDatabind.etLoginPhone.getText())) {
                    ToastUtil.show("请输入正确的手机号");
                    return;
                }
                mViewModel.getLoginCode(mDatabind.etLoginPhone.getText().toString());
            }
        });

        //切换环境
        mDatabind.butChange.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                changeClickCount++;
                if (changeClickCount > 10) {
                    ToastUtil.show(changeClickCount);
                }
                if (changeClickCount == 15) {
                    String[] strings = {"正式环境", "测试环境", "开发环境"};
                    CommonUtils.showCenterListWith(LoginActivity.this, 10, "请选择环境", strings, new OnSelectListener() {
                        @Override
                        public void onSelect(int position, String text) {
                            CommonUtils.changeEnvironment(position);
                        }
                    });
                    changeClickCount = 0;
                }
            }
        });

        //一键登录
        mDatabind.tvOneLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Constant.AUTH_ALI) {
                    phoneNumberLogin();
                }
            }
        });
    }

    @Override
    public void initObserver() {
        //输入框的监听
        mDatabind.etLoginPhone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.toString().length() > 0) {
                    mDatabind.ivLoginClean.setVisibility(View.VISIBLE);
                } else {
                    mDatabind.ivLoginClean.setVisibility(View.GONE);
                }
            }
        });

    }

    @Override
    public void onRequestSuccess() {

        //拿到数据
        mViewModel.getSelectUserInfo().observe(this, new Observer<UserInfo>() {
            @Override
            public void onChanged(UserInfo userInfo) {
                MMKVHelper.putString(ConstantMMVK.TOKEN, userInfo.getToken());
                MMKVHelper.putString(ConstantMMVK.USER_INFO, JSON.toJSONString(userInfo));
                CommonUtils.updateLocalUserData(userInfo);
                ActivityForwardUtil.startActivity(MainActivity.class);
                AppExtKt.finishActivity(LoginActivity.class);
            }
        });

        //请求回来的身份
        mViewModel.getUserInfo().observe(this, new Observer<UserInfo>() {
            @Override
            public void onChanged(UserInfo userInfo) {
                if (userInfo.getCompany_list() != null && userInfo.getCompany_list().size() > 1) {//说明有企业  并且是大于1个的，都需要去选择
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("user_info", userInfo);
                    ActivityForwardUtil.startActivity(SelectCompanyActivity.class, bundle);
                    return;
                }
                HashMap<String, String> hashMap = new HashMap<>();
                hashMap.put("company_uuid", "" + userInfo.getCompany_list().get(0).getUuid());
                hashMap.put("login_user_uuid", "" + userInfo.getLogin_user_uuid());
                mViewModel.requestCompany(hashMap);
            }
        });

        //验证码
        mViewModel.getCodeEntity().observe(this, new Observer<CodeEntity>() {
            @Override
            public void onChanged(CodeEntity codeEntity) {
                ToastUtil.show("验证码已发送");
                mDatabind.etLoginPass.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mDatabind.etLoginPass.requestFocus();
                        KeyboardUtils.showSoftInput(mDatabind.etLoginPass);
                    }
                }, 1000);
                mDatabind.butLoginCode.setClickable(false);
                startCountdown(mDatabind.butLoginCode);
            }
        });
    }

    /**
     * 启动一个定时器
     */
    public void startCountdown(TextView button) {
        final int totalTime = 60;
        disposable = Observable.interval(1, TimeUnit.SECONDS)
                .take(totalTime + 1)
                .map(aLong -> totalTime - aLong.intValue())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Integer>() {
                    @Override
                    public void accept(Integer time) throws Exception {
                        button.setText(time + "s 后再次获取");
                        if (time == 0) {
                            // 倒计时结束后的操作
                            mDatabind.butLoginCode.setClickable(true);
                            button.setText("再次获取");
                        }
                    }
                });
    }

    private void initAliAuthLogin() {
        //初始化一键授权的内容
        /**
         * 初始化 DoraemonManager
         *
         * @param context
         * @param appId             应用密钥，找到安全认证应用，应用详情中拷贝 应用ID
         * @param appKey                   应用密钥，找到安全认证应用，点击 复制秘钥
         * @param fetchAccessTokenCallBack 获取accessToken回调
         */
        DoraemonManager.init(this, "724586a781", "V1hxUGZYMHlnZ1dkdjZYNg==", new FetchAccessTokenCallBackImpl(), new DoraemonCallback() {
            @Override
            public void onFailure(Exception e) {
                LogExtKt.logE("初始化失败" + e.getMessage(), "");

            }

            @Override
            public void onSuccess(Object o) {
                LogExtKt.logE("初始化成功", "");
                Constant.AUTH_ALI = true;
                mDatabind.llPassLayout.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        checkPhone();
                        phoneNumberLogin();
                    }
                }, 1000);
            }
        });
    }

    /**
     * 检查本级是否支持 一件登录
     */
    private void checkPhone() {
        /**
         * 检查本机是否支持一键登录
         * @param i
         * @param doraemonCallback
         */
        DoraemonManager.checkEnvAvailable(PhoneNumberAuthHelper.SERVICE_TYPE_LOGIN, new DoraemonCallback() {
            @Override
            public void onFailure(Exception e) {
                LogExtKt.logE("checkEnvAvailable失败！" + e.getMessage(), TAG);
            }

            @Override
            public void onSuccess(Object data) {
                LogExtKt.logE("checkEnvAvailable成功！" + data, TAG);
                mDatabind.tvOneLogin.setVisibility(View.VISIBLE);
            }
        });
    }

    /**
     * 本机手机号码一键登录
     */
    private void phoneNumberLogin() {
        BaseUIConfig baseUIConfig = new FullPortConfig(this);
        DoraemonManager.phoneNumberLogin(this, new DoraemonCallback() {
            @Override
            public void onFailure(Exception e) {
                Log.i(TAG, "phoneNumberLogin " + e.getMessage());
                LogExtKt.logE("phoneNumberLogin！error" + e.getMessage(), TAG);
            }

            @Override
            public void onSuccess(Object data) {
                Log.i(TAG, "phoneNumberLogin success" + data.toString());
                LogExtKt.logE("phoneNumberLogin！成功--- success - " + data.toString(), TAG);
                HashMap<String, String> hashMap = new HashMap<>();
                hashMap.put("jwt_id_token", "" + data);
                hashMap.put("auth_uuid", "" + MMKVHelper.getString(ConstantMMVK.ALI_AUTH_UUID));
                mViewModel.loginAliApp(hashMap);
            }
        }, baseUIConfig);
    }

    public String md5(String string) {
        if (TextUtils.isEmpty(string)) {
            return "";
        }
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
            byte[] bytes = md5.digest(string.getBytes());
            String result = "";
            for (byte b : bytes) {
                String temp = Integer.toHexString(b & 0xff);
                if (temp.length() == 1) {
                    temp = "0" + temp;
                }
                result += temp;
            }
            return result;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }

    @Override
    public void onBackPressed() {
        if (backPressedTime + TIME_INTERVAL > System.currentTimeMillis()) {
            super.onBackPressed();
//            KtxActivityManger.INSTANCE.finishAllActivity();
            System.exit(0);
        } else {
            ToastUtil.show("再次点击返回按钮退出应用");
        }

        backPressedTime = System.currentTimeMillis();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (disposable != null) {
            disposable.dispose();
        }
    }
}